package _05_二叉树;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class _145_二叉树的后序遍历复习 {

    // 二叉树后序遍历，非递归
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> results = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode prev = null;
        while (true) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                // 弹出元素
                TreeNode node = stack.peek();
                // 查看当前元素，是否存在右节点
                if (node.right != null) {
                    // 当成根节点对待
                    root = node.right;
                } else if (prev == null || prev == node.left){
                    if (stack.isEmpty()) {
                        break;
                    } else {
                        node = stack.pop();
                        results.add(node.val);
                        prev = node;
                    }
                }
            }
        }
        return results;
    }

}
